import React, {useEffect, useState} from 'react';
import 'antd/dist/reset.css';
import './App.css';
import {useLocation, useNavigate} from 'react-router-dom';
import {Button, Layout, Menu, theme} from 'antd';
import {MenuFoldOutlined, MenuUnfoldOutlined, UserOutlined, ClusterOutlined} from '@ant-design/icons';
import UserTable from "./pages/UserTable";
import UserOpTable from "./pages/UserOpTable";
import DeptTable from "./pages/DeptTable";

const {Header, Content, Footer, Sider} = Layout;

const defaultKey = '/page/user/edit';
const items = [
  {
    label: "用户管理",
    key: "1",
    path: "SubMenuSJSC",
    icon: <UserOutlined />,
    component: <UserTable />,
    children: [
      { label: "用户管理", key: "/page/user/edit", path: "/page/user/edit", icon: null, component: <UserTable /> },
      { label: "权限管理", key: "/page/user/op", path: "/page/user/op", icon: null, component: <UserOpTable /> },
    ],
  },
  { label: "部门管理", key: "/page/dept/edit", path: "/page/dept/edit", icon: <ClusterOutlined />, component: <DeptTable /> },
];

// 找到对应的组件并设置为当前组件
const findComponent = (items, key) => {
  for (const item of items) {
    if (item.key === key) {
      return item.component;
    }
    if (item.children) {
      const foundComponent = findComponent(item.children, key);
      if (foundComponent) {
        return foundComponent;
      }
    }
  }
  return undefined;
};

const findComponentByPath = (items, path) => {
  for (const item of items) {
    if (item.path === path) {
      return item.component;
    }
    if (item.children) {
      const foundComponent = findComponentByPath(item.children, path);
      if (foundComponent) {
        return foundComponent;
      }
    }
  }
  return undefined;
};

// 找到对应的 path 并跳转
const findMenuItem = (items, key) => {
  for (const item of items) {
    if (item.key === key) return item;
    if (item.children) {
      const found = findMenuItem(item.children, key);
      if (found) return found;
    }
  }
  return null;
};

const App = () => {
  const navigate = useNavigate();
  const [currentComponent, setCurrentComponent] = useState();
  const [collapsed, setCollapsed] = useState(() => {
    // 从 localStorage 读取折叠状态，默认为 false
    const savedCollapsed = localStorage.getItem('menuCollapsed');
    return savedCollapsed ? JSON.parse(savedCollapsed) : true;
  });
  const [openKeys, setOpenKeys] = useState(() => {
    // 从 localStorage 读取 openKeys，默认为空数组
    const savedOpenKeys = localStorage.getItem('menuOpenKeys');
    return savedOpenKeys ? JSON.parse(savedOpenKeys) : [];
  });
  const location = useLocation();


  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  useEffect(() => {
    // 监听 collapsed 状态的变化，并保存到 localStorage
    localStorage.setItem('menuCollapsed', JSON.stringify(collapsed));

    // 监听 openKeys 的变化，并保存到 localStorage
    localStorage.setItem('menuOpenKeys', JSON.stringify(openKeys));

    setCurrentComponent(findComponentByPath(items, location.pathname));
    if (!findComponentByPath(items, location.pathname)) {
      navigate(defaultKey);
    }
  }, [collapsed, openKeys, location.pathname, navigate]);

  const onMenuClick = (e) => {
    const component = findComponent(items, e.key);
    if (component) {
      setCurrentComponent(component);
    }

    const menuItem = findMenuItem(items, e.key);
    if (menuItem && menuItem.path) {
      navigate(menuItem.path);
    }
  };

  const onOpenChange = (keys) => {
    setOpenKeys(keys);
  };

  return (
    <Layout>
      <Header style={{ padding: 0, background: colorBgContainer, height: 48, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: "18px",
              width: 48,
              height: 48,
              padding: 0,
            }}
          />
          <span style={{ fontSize: '18px', fontWeight: 'bold', marginLeft: 16, lineHeight: '48px' }}>用户管理系统</span>
        </div>
      </Header>

      <Content>
        <Layout>
          <Sider
            collapsible
            collapsed={collapsed}
            onCollapse={(value) => setCollapsed(value)}
            collapsedWidth={48}
          >
            <div className="demo-logo-vertical" />
            <Menu
              theme="dark"
              defaultSelectedKeys={[findComponentByPath(items, location.pathname) ? location.pathname : defaultKey]}
              mode="inline"
              items={items}
              onClick={onMenuClick}
              openKeys={openKeys}
              onOpenChange={onOpenChange}
            />
          </Sider>
          <Layout>
            <Content style={{ margin: "16px 16px 0 16px", minHeight: "calc(100vh - 64px)" }}>
              <div
                style={{
                  padding: 24,
                  minHeight: "calc(100vh - 64px)",
                  background: colorBgContainer,
                  borderRadius: borderRadiusLG,
                }}
              >
                {currentComponent}
              </div>
            </Content>
            <Footer style={{ textAlign: "center", height: 64 }} >
              东方晨旭 ©{new Date().getFullYear()}
            </Footer>
          </Layout>
        </Layout>
      </Content>
    </Layout>
  );
};

export default App;